package com.sumu.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.sumu.adapter.AdvPagerAdapter;
import com.sumu.adapter.CategoryAdapter;
import com.sumu.adapter.HomeAdapter;
import com.sumu.baidunuomi.R;
import com.sumu.bean.Category;
import com.sumu.bean.HomeBean;
import com.sumu.bean.LikeBean;
import com.sumu.bean.LikeBean.Data.Tuan_list;
import com.sumu.utils.AppConstants;
import com.sumu.utils.VolleyHelper;
import com.sumu.view.AutoScrollViewPager;

public class HomeFragment extends Fragment implements
		OnRefreshListener2<ListView> {
	private Context context;
	@ViewInject(R.id.home_fragment_listview)
	private PullToRefreshListView ptfListView;
	@ViewInject(R.id.btn_home_location)
	private Button button_location;
	// private ListView ptfListView;
	public LocationClient mLocationClient = null;
	private LocationClientOption clientOption = new LocationClientOption();
	private List<Tuan_list> list = new ArrayList<Tuan_list>();
	private String url;
	private HomeAdapter adapter;

	public static HomeFragment getInstance(String url) {
		HomeFragment fragment = new HomeFragment();
		Bundle bundle = new Bundle();
		bundle.putString("url", url);
		fragment.setArguments(bundle);
		return fragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		context = getActivity();
		Bundle bundle = getArguments();
		url = bundle.getString("url");

	}

	public void initLocation() {
		clientOption.setCoorType("bd09ll");
		clientOption.setOpenGps(true);
		clientOption.setLocationMode(LocationMode.Battery_Saving);
		clientOption.setScanSpan(3000);
		clientOption.setTimeOut(5000);

		mLocationClient = new LocationClient(context.getApplicationContext()); // 声明LocationClient类
		mLocationClient.setLocOption(clientOption);

		mLocationClient.registerLocationListener(new BDLocationListener() {

			@Override
			public void onReceiveLocation(BDLocation location) {
				// TODO Auto-generated method stub
				button_location.setText(location.getCity());

			}
		});

		mLocationClient.start();
		if (mLocationClient != null && mLocationClient.isStarted()) {
			// //发送位置请求
			int i = mLocationClient.requestLocation();

		}
		

	}
//	new 

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_home_layout, container,
				false);
		ViewUtils.inject(this, view);
		initLocation();
		adapter = new HomeAdapter(list, context);
		ptfListView.setMode(Mode.PULL_FROM_START);
		ptfListView.setOnRefreshListener(this);
		ptfListView.setAdapter(adapter);
		ListView listView = ptfListView.getRefreshableView();
		listView.addHeaderView(createHeaderView());
		// listView.addFooterView(v);

		// createData();
		getData();
		return view;
	}

	private View createHeaderView() {
		// TODO Auto-generated method stub
		View view = View.inflate(context, R.layout.headview_home_layout, null);
		final ViewHolder holder = new ViewHolder();
		ViewUtils.inject(holder, view);

		StringRequest request = new StringRequest(AppConstants.URL_HOME,
				new Listener<String>() {

					@Override
					public void onResponse(String response) {
						// TODO Auto-generated method stub
						HomeBean homeBean = (HomeBean) JSONObject.parseObject(
								response, HomeBean.class);
						holder.imageView1.setImageUrl(homeBean.getData()
								.getSpecial().get(0).getPicture_url(),
								VolleyHelper.getIntstance().getImageLoader());
						holder.imageView2.setImageUrl(homeBean.getData()
								.getSpecial().get(1).getPicture_url(),
								VolleyHelper.getIntstance().getImageLoader());
						holder.imageView_user.setImageUrl(homeBean.getData()
								.getRecommend().get(0).getMan_pic(),
								VolleyHelper.getIntstance().getImageLoader());
						holder.imageView_show.setImageUrl(homeBean.getData()
								.getRecommend().get(0).getRecommend_image(),
								VolleyHelper.getIntstance().getImageLoader());
						holder.textView_content.setText(homeBean.getData()
								.getRecommend().get(0).getMan_name()
								+ "  "
								+ homeBean.getData().getRecommend().get(0)
										.getMan_desc());
						holder.textView_location.setText(homeBean.getData()
								.getRecommend().get(0).getRecommend_title());
						// 设置autoScrollViewPager
						List<NetworkImageView> imageViews = new ArrayList<NetworkImageView>();
						for (int i = 0; i < homeBean.getData().getBanners()
								.size(); i++) {
							NetworkImageView networkImageView = new NetworkImageView(
									context);
							networkImageView.setImageUrl(homeBean.getData()
									.getBanners().get(i).getPicture_url(),
									VolleyHelper.getIntstance()
											.getImageLoader());
							imageViews.add(networkImageView);
						}
						AdvPagerAdapter adapter = new AdvPagerAdapter(
								imageViews);
						holder.autoScrollViewPager.startAutoScroll();
						holder.autoScrollViewPager.setAdapter(adapter);
						// 设置gridview
						List<Category> categories = homeBean.getData()
								.getCategory();
						CategoryAdapter adapter2 = new CategoryAdapter(
								categories, context);
						holder.gridView.setAdapter(adapter2);
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						// TODO Auto-generated method stub

					}
				});
		request.setTag(this);
		VolleyHelper.getIntstance().addRequest(request);

		return view;
	}

	public class ViewHolder {
		@ViewInject(R.id.viewpager_adv)
		AutoScrollViewPager autoScrollViewPager;
		@ViewInject(R.id.gridView_category)
		GridView gridView;
		@ViewInject(R.id.imagebutton_home_special1)
		NetworkImageView imageView1;
		@ViewInject(R.id.imagebutton_home_special2)
		NetworkImageView imageView2;
		@ViewInject(R.id.icon_home_headview)
		NetworkImageView imageView_user;
		@ViewInject(R.id.imageView_home_headview)
		NetworkImageView imageView_show;
		@ViewInject(R.id.textView_home_headview_location)
		TextView textView_location;
		@ViewInject(R.id.textView_home_headview_content)
		TextView textView_content;
		@ViewInject(R.id.button_home_headview_more)
		Button button_more;

	}

	// 用Xutils去解析
	public void createData() {
		HttpUtils httpUtils = new HttpUtils();
		httpUtils.send(HttpMethod.GET, url, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				// TODO Auto-generated method stub
				System.out.println("httpUtils错误");
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				// TODO Auto-generated method stub
				System.out.println(arg0.result);
			}
		});
	}

	/**
	 * 用Volley去解析
	 */
	private void getData() {
		// TODO Auto-generated method stub
		if (com.sumu.utils.HttpUtils.getNetworkState(context)) {
			StringRequest request = new StringRequest(url,
					new Listener<String>() {

						@Override
						public void onResponse(String response) {
							// TODO Auto-generated method stub
							LikeBean likeBean = JSONObject.parseObject(
									response, LikeBean.class);
							System.out.println("----------LikeBean--------"
									+ likeBean);
							List<Tuan_list> tuan_lists = likeBean.getData()
									.getTuan_list();
							list.addAll(tuan_lists);
							adapter.notifyDataSetChanged();
							ptfListView.onRefreshComplete();

						}

					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							// TODO Auto-generated method stub
							System.out.println("错了");
						}
					});
			request.setTag(this);
			VolleyHelper.getIntstance().addRequest(request);

		} else {
			Toast.makeText(context, "请检查网络！", Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		VolleyHelper.getIntstance().getRequestQueue().cancelAll(this);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		list.clear();
		getData();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub

	}

}
